<!--
 * @Descripttion: 发行商管理-新建发行商
 * @Author: binbin binbin@ssc-hn.com
 * @Date: 2025-03-13
 * @LastEditors: Bart 1714877505@qq.com
 * @LastEditTime: 2025-03-27
-->
<template>
  <div class="integral-add-box">
    <div class="add-header">
      <arrow-left-outlined :style="{ 'font-weight': 'bold', 'margin-right': '18px' }" @click="router.back()" />
      <span>新建发行商</span>
    </div>
    <a-divider />
    <a-form :model="formState" :rules="rules" layout="horizontal" ref="formRef" name="add_form" labelAlign="left">
      <div class="detail-list">
        <div class="detail-box">
          <div class="box-title"> <span>积分信息</span> </div>
          <a-form-item label="积分名称" name="coinName">
            <a-input v-model:value="formState.coinName" allow-clear />
          </a-form-item>
          <a-form-item label="积分代号" name="coinSymbol">
            <a-input v-model:value="formState.coinSymbol" allow-clear />
          </a-form-item>
          <a-form-item label="区块链" name="chainType">
            <a-radio-group v-model:value="formState.chainType">
              <a-radio value="BASS">BASS</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="积分类型" name="ratio">
            <div style="margin-bottom: 12px">
              <a-radio-group v-model:value="formState.moduleType">
                <a-radio :value="1">普通积分</a-radio>
                <a-radio :value="2">稳定积分（与法币兑换）</a-radio>
              </a-radio-group>
            </div>
            <a-input-number v-if="formState.moduleType === 2" v-model:value="formState.ratio" addon-before="1积分=" addon-after="元" />
          </a-form-item>
          <a-form-item label="发行数量" name="integralCount">
            <a-input-number style="width: 100%" v-model:value="formState.integralCount" :precision="0" :min="1" :max="999999999" :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')" :parser="(value) => value.replace(/\$\s?|(,*)/g, '')" />
          </a-form-item>
          <a-form-item label="积分精度" name="coinDecimals">
            <a-input-number style="width: 100%" v-model:value="formState.coinDecimals" :precision="0.00000001" :min="1" :max="999999999" :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')" :parser="(value) => value.replace(/\$\s?|(,*)/g, '')" />
          </a-form-item>
          <a-form-item class="w-[50%]" name="coinIcon" label="积分LOGO" extra="建议尺寸200*200像素">
            <a-upload v-model:file-list="fileList" name="file" list-type="picture-card" :maxCount="1" class="avatar-uploader" :action="uploadApi" :headers="{ authorization: token }" :before-upload="beforeUpload" @change="handleChange($event, 1)">
              <div>
                <loading-outlined v-if="variable.uploadLoading" :style="{ color: '#13c2c2' }" />
                <plus-outlined v-else :style="{ color: '#13c2c2' }" />
                <div class="ant-upload-text">上传图片</div>
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item label="项目官网" name="officialSite">
            <a-input v-model:value="formState.officialSite" allow-clear />
          </a-form-item>
          <a-form-item label="积分简介" name="introduction">
            <a-textarea :rows="4" v-model:value="formState.introduction" allow-clear :maxlength="300" />
          </a-form-item>
        </div>
        <div class="detail-box">
          <div class="box-title"> <span>存管银行</span> </div>
          <a-form-item label="存管银行" name="supervisionType">
            <a-select v-model:value="formState.supervisionType" placeholder="请选择类别">
              <a-select-option :key="item.companyId" v-for="item in supervisionOption" :value="item.companyId">
                {{ item.companyName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="监管账号" name="supervisionAccount">
            <a-input v-model:value="formState.supervisionAccount" allow-clear />
          </a-form-item>
          <a-form-item class="w-[50%]" name="supervisionFiles" label="存管文件" extra="">
            <a-upload v-model:file-list="supervisionFilesList" name="file" list-type="picture-card" :maxCount="1" class="avatar-uploader" :action="uploadApi" :headers="{ authorization: token }" :before-upload="beforeUploadFile" @change="handleChange($event, 2)">
              <div>
                <loading-outlined v-if="variable.supervisionUploadLoading" :style="{ color: '#13c2c2' }" />
                <plus-outlined v-else :style="{ color: '#13c2c2' }" />
                <div class="ant-upload-text">上传文件</div>
              </div>
            </a-upload>
          </a-form-item>
        </div>
        <div class="detail-box">
          <div class="box-title"> <span>监管机构</span> </div>
          <a-form-item label="监管机构" name="companyId">
            <a-select v-model:value="formState.companyId" placeholder="请选择类别">
              <a-select-option :key="item.companyId" v-for="item in superOption" :value="item.companyId">
                {{ item.companyName }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item class="w-[50%]" name="superFiles" label="监管文件" extra="">
            <a-upload v-model:file-list="superFilesList" name="file" list-type="picture-card" :maxCount="1" class="avatar-uploader" :action="uploadApi" :headers="{ authorization: token }" :before-upload="beforeUploadFile" @change="handleChange($event, 3)">
              <div>
                <loading-outlined v-if="variable.superFilesUploadLoading" :style="{ color: '#13c2c2' }" />
                <plus-outlined v-else :style="{ color: '#13c2c2' }" />
                <div class="ant-upload-text">上传文件</div>
              </div>
            </a-upload>
          </a-form-item>
        </div>
      </div>
    </a-form>
    <div class="btn-wrap">
      <a-space>
        <a-button type="primary" @click="confirm(2)">提交</a-button>
        <a-button type="primary" @click="confirm(1)">保存</a-button>
        <a-button type="default" @click="handleCancle">取消</a-button>
      </a-space>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ArrowLeftOutlined } from '@ant-design/icons-vue'
  import { message, Upload } from 'ant-design-vue'
  import { Rule } from 'ant-design-vue/lib/form'
  import { onMounted, reactive, ref } from 'vue'
  import { useRoute, useRouter } from 'vue-router'

  import { requestGetCoinAuditInfo, requestGetCompanyList, requestSaveIntegralIssuer } from '/@/api/integral/integralIssuer'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { getToken } from '/@/storage'
  const token = getToken() || ''
  const uploadApi = `${import.meta.env.VITE_BASE_API_PATH}/contentFile/upload/V1`
  const router = useRouter()
  const route = useRoute()
  const coinId = route.query.coinId
  const detailId = route.query.id
  const formRef = ref()
  const formState: any = ref({
    coinName: '',
    introduction: '',
    coinIcon: '',
    supervisionFiles: '',
    superFiles: '',
    coinSymbol: '',
    integralCount: '',
    coinDecimals: '',
    officialSite: '',
    supervisionAccount: '',
    chainType: 'BASS',
    moduleType: 1,
    companyId: null,
    supervisionType: null,
    ratio: '',
    chainId: 4,
    supervisionInfoList: [],
  })
  const supervisionOption = ref<GetCompanyListTypes.IResponse[]>([])
  const superOption = ref<GetCompanyListTypes.IResponse[]>([])
  const validate = async (_rule: Rule, value: string) => {
    if (formState.value.moduleType === 2) {
      if (value === '') {
        return Promise.reject('请输入积分转换比例')
      } else {
        return Promise.resolve()
      }
    } else {
      return Promise.resolve()
    }
  }
  /** 自定义校验规则 */
  const rules: Record<string, Rule[]> = {
    coinName: [
      { required: true, message: '请输入积分名称' },
      { max: 50, message: '最多不能超过50个字符' },
    ],
    coinSymbol: [
      { required: true, message: '请输入积分代号' },
      { max: 10, message: '最多不能超过10个字符' },
    ],
    coinIcon: [{ required: true, message: '请上传积分LOGO' }],
    password: [{ required: true, message: '请输入密码' }],
    integralCount: [{ required: true, message: '请输入发行数量' }],
    coinDecimals: [{ required: true, message: '请输入积分精度' }],
    officialSite: [{ required: false, message: '请输入项目官网' }],
    appType: [{ required: true, message: '请选择监管银行机构' }],
    companyId: [{ required: true, message: '请选择监管机构' }],
    introduction: [
      { required: true, message: '请输入积分简介' },
      { max: 300, message: '最多不能超过300个字符' },
    ],
    chainType: [{ required: true, message: '请选择区块链' }],
    ratio: [{ required: true, validator: validate, trigger: ['change', 'blur'] }],
    supervisionAccount: [{ required: true, message: '请输入监管账号' }],
    supervisionFiles: [{ required: true, message: '请上传文件' }],
    superFiles: [{ required: true, message: '请上传文件' }],
    supervisionType: [{ required: true, message: '请选择存管银行' }],
  }

  const fileList = ref<any>([])
  const supervisionFilesList = ref<any>([])
  const superFilesList = ref<any>([])

  const variable = reactive({
    confirmLoading: false,
    uploadLoading: false,
    supervisionUploadLoading: false,
    superFilesUploadLoading: false,
  })

  const handleCancle = () => {
    router.back()
  }
  const beforeUpload = (file) => {
    const fileSizeKB = file.size / 1024
    const isPng = ['.jpg', '.jpeg', '.png'].includes(file.name.substr(file.name.lastIndexOf('.')).toLowerCase())
    if (!isPng) {
      message.error('支持格式：.jpg .jpeg .png')
      return false || Upload.LIST_IGNORE
    } else if (fileSizeKB > 300) {
      message.error('文件大小超过300KB，请选择一个较小的文件。')
      return false || Upload.LIST_IGNORE
    } else {
      return true
    }
  }

  const beforeUploadFile = (file) => {
    const isJpgOrPng = ['.jpg', '.jpeg', '.png', '.rar', '.zip', '.doc', '.docx', '.pdf'].includes(file.name.substr(file.name.lastIndexOf('.')).toLowerCase())
    if (!isJpgOrPng) {
      message.error('支持格式：.jpg .jpeg .png .rar .zip .doc .docx .pdf')
    }
    const isLt2M = file.size / 1024 / 1024 < 50
    if (!isLt2M) {
      message.error('单个文件不能超过50M')
    }
    return isJpgOrPng && isLt2M
  }

  const handleChange = (info, type) => {
    if (info.file.status === 'uploading') {
      switch (type) {
        case 1:
          variable.uploadLoading = true
          break
        case 2:
          variable.supervisionUploadLoading = true
          break
        case 3:
          variable.superFilesUploadLoading = true
          break
      }
      return
    }
    if (info.file.status === 'done') {
      if (info.file.response.responseData && info.file.response.responseData !== null) {
        switch (type) {
          case 1:
            formState.value.coinIcon = info.file.response.responseData
            variable.uploadLoading = false
            break
          case 2:
            formState.value.supervisionFiles = info.file.response.responseData
            variable.supervisionUploadLoading = false
            break
          case 3:
            formState.value.superFiles = info.file.response.responseData
            variable.superFilesUploadLoading = false
            break
        }
        message.success('上传成功')
      } else {
        switch (type) {
          case 1:
            variable.uploadLoading = false
            break
          case 2:
            variable.supervisionUploadLoading = false
            break
          case 3:
            variable.superFilesUploadLoading = false
            break
        }
        message.error(info.file.response.responseMessage || '上传错误')
      }
    }
    if (info.file.status === 'error') {
      switch (type) {
        case 1:
          variable.uploadLoading = false
          break
        case 2:
          variable.supervisionUploadLoading = false
          break
        case 3:
          variable.superFilesUploadLoading = false
          break
      }
      message.error(info.file.response.responseMessage || '上传错误')
    }
  }

  const getInfoById = async () => {
    const { responseCode, responseData } = await requestGetCoinAuditInfo({
      coinAuditInfoId: Number(detailId),
    })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      formState.value = { ...responseData }
      if (responseData?.coinIcon) {
        fileList.value = [
          {
            name: responseData.coinIcon.substring(responseData.coinIcon.lastIndexOf('/') + 1),
            status: 'done',
            url: responseData.coinIcon,
          },
        ]
      }

      if (responseData?.supervisionInfoList && responseData?.supervisionInfoList.length) {
        responseData?.supervisionInfoList.forEach((item) => {
          if (item.supervisionType === 1) {
            formState.value.supervisionType = item.companyId
            formState.value.supervisionAccount = item.supervisionAccount
            formState.value.supervisionFiles = item.supervisionFiles
            supervisionFilesList.value = [
              {
                name: item.supervisionFiles?.substring(item.supervisionFiles.lastIndexOf('/') + 1),
                status: 'done',
                url: item.supervisionFiles,
              },
            ]
          } else if (item.supervisionType === 2) {
            formState.value.companyId = item.companyId
            formState.value.superFiles = item.supervisionFiles
            superFilesList.value = [
              {
                name: item.supervisionFiles?.substring(item.supervisionFiles.lastIndexOf('/') + 1),
                status: 'done',
                url: item.supervisionFiles,
              },
            ]
          }
        })
      }
    }
  }

  const confirm = (type) => {
    formRef.value
      .validate()
      .then(async () => {
        const _supervisionInfoList =
          formState.value.supervisionInfoList && formState.value.supervisionInfoList.length
            ? formState.value.supervisionInfoList.map((item) => {
                const _item = item
                if (_item.supervisionType === 1) {
                  _item.companyId = formState.value.supervisionType
                  _item.supervisionAccount = formState.value.supervisionAccount
                  _item.supervisionFiles = formState.value.supervisionFiles
                } else if (_item.supervisionType === 2) {
                  _item.companyId = formState.value.companyId
                  _item.supervisionFiles = formState.value.superFiles
                }
                return _item
              })
            : [
                {
                  supervisionType: 1,
                  companyId: formState.value.supervisionType,
                  supervisionAccount: formState.value.supervisionAccount,
                  supervisionFiles: formState.value.supervisionFiles,
                },
                {
                  supervisionType: 2,
                  companyId: formState.value.companyId,
                  supervisionFiles: formState.value.superFiles,
                },
              ]
        const params: any = {
          ...formState.value,
          supervisionInfoList: _supervisionInfoList,
          saveType: type,
        }
        if (detailId) {
          params.auditId = detailId
          params.coinId = coinId
        }
        delete params.supervisionType
        delete params.supervisionAccount
        delete params.supervisionFiles
        delete params.companyId
        delete params.superFiles
        variable.confirmLoading = true
        const { responseCode } = await requestSaveIntegralIssuer({ ...params }).finally(() => {
          variable.confirmLoading = false
        })

        if (responseCode === HttpCodeEnum.SUCCESS) {
          if (detailId) {
            message.success(`操作成功`)
          } else {
            message.success(`操作成功`)
          }
          router.back()
        }
      })
      .catch((res) => {
        console.log('catch: ', res)
      })
  }
  /**
   * 获取存管银行
   */
  const getSupervisionOptionList = async () => {
    const { responseCode, responseData } = await requestGetCompanyList({
      companyLabel: 4,
    })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      supervisionOption.value = responseData
    }
  }

  /**
   * 获取监管机构
   */
  const getSuperOptionList = async () => {
    const { responseCode, responseData } = await requestGetCompanyList({
      companyLabel: 5,
    })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      superOption.value = responseData
    }
  }

  onMounted(() => {
    getSupervisionOptionList()
    getSuperOptionList()
    if (detailId) {
      getInfoById()
    }
  })
</script>

<style lang="less" scoped>
  .integral-add-box {
    background: #fff;
    padding: 24px;
    min-height: 100%;

    .add-header {
      font-size: 18px;
      font-weight: 500;
      color: #000;
    }

    .detail-list {
      display: flex;
      flex-direction: column;

      .detail-box {
        display: flex;
        flex-direction: column;

        .box-title {
          width: 100%;
          display: flex;
          align-items: center;
          margin-bottom: 20px;

          span {
            font-size: 16px;
            color: #000;
            font-weight: 600;
            display: flex;
            align-items: center;
          }

          span::before {
            content: '';
            width: 4px;
            height: 16px;
            background: #006aff;
            display: inline-block;
            margin-right: 10px;
          }
        }

        .approve-detail {
          display: flex;
          flex-direction: column;

          .approve-btn {
            display: flex;
            justify-content: end;
            flex-direction: row;
            align-items: center;
            margin-top: 20px;

            .ant-btn {
              & + * {
                margin-left: 8px;
              }
            }
          }

          .approve-content {
            display: flex;
            align-items: center;
            justify-content: center;

            .approve-info {
              display: flex;
              flex-direction: column;

              .approve-title {
                font-size: 24px;
                font-weight: 600;
                color: #000;
              }

              .approve-name {
                width: 100%;
                display: flex;
              }
            }
          }
        }
      }
    }

    .btn-wrap {
      display: flex;
      justify-content: center;
    }
  }
</style>
